#include "spkbutton.h"

#include <QPainter>

SpkButton::SpkButton(QString strpixnormal, QString strpixenter, QString strpixleave, QWidget *parent)
    : QPushButton(parent)
{
    QPixmap pixnormal(strpixnormal);
    QPixmap pixenter(strpixenter);
    QPixmap pixleave(strpixleave);

    setCursor(Qt::PointingHandCursor);
    m_leave = !(m_enter = false);
    m_enterIndex = m_leaveIndex = 0;

    m_pixnormal = pixnormal;
    for(int i=0;i<10;i++)//进入
    {
        m_enterlist << pixenter.copy(i*(pixenter.width()/10),0,pixenter.width()/10,pixenter.height());
    }
    for(int j=0;j<8;j++)//离开
    {
        m_leavelist << pixleave.copy(j*(pixleave.width()/8),0,pixleave.width()/8,pixleave.height());
    }

    m_enteranimation=new QPropertyAnimation(this,"");
    m_enteranimation->setStartValue(0);
    m_enteranimation->setEndValue(9);
    m_enteranimation->setDuration(600);
    connect(m_enteranimation,SIGNAL(valueChanged(QVariant)),this,SLOT(entervaluechange(QVariant)));

    m_leaveanimation=new QPropertyAnimation(this,"");
    m_leaveanimation->setStartValue(0);
    m_leaveanimation->setEndValue(7);
    m_leaveanimation->setDuration(600);
    connect(m_leaveanimation,SIGNAL(valueChanged(QVariant)),this,SLOT(leavevaluechange(QVariant)));
}

SpkButton::~SpkButton()
{
    delete m_leaveanimation;
    delete m_enteranimation;
}

void SpkButton::enterEvent(QEvent *event)
{
    m_enter = !(m_leave = false);
    m_enteranimation->start();
}

void SpkButton::leaveEvent(QEvent *event)
{
    m_leave = !(m_enter = false);
    m_leaveanimation->start();
}

void SpkButton::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::RenderHint::SmoothPixmapTransform, true);
    if (m_enter)
        painter.drawPixmap(rect(), m_enterlist.at(m_enterIndex));
    if (m_leave)
        painter.drawPixmap(rect(), m_leavelist.at(m_leaveIndex));
}

void SpkButton::entervaluechange(QVariant var){
    m_enterIndex = var.toInt();
    update();
}

void SpkButton::leavevaluechange(QVariant var){
    m_leaveIndex=var.toInt();
    update();
}
